import { pageListTruckOrderServiceFees, getTruckOrderServiceFeeinfo } from '@/services/order/order_api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
    ProTable,
    TableDropdown
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal, Popconfirm, Card, Select, DatePicker, Form, Space, Collapse, Tabs, Typography } from 'antd';
import type { GetProp, TableProps } from "antd";
import React, { useRef, useState, useEffect } from 'react';
import type { RangePickerProps } from 'antd/es/date-picker';
import { TruckOrderServiceFeeVO,TruckOrderServiceFeeReqVO } from '../types'
import { DownOutlined, UpOutlined, SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import type { SorterResult } from "antd/es/table/interface";
import qs from 'qs';
import { formatToLocalTime,toUTC } from '@/utils/time';
const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

type TablePaginationConfig = Exclude<
    GetProp<TableProps, "pagination">,
    boolean
>;

interface TableParams {
    pagination?: TablePaginationConfig;
    sortField?: SorterResult<any>["field"];
    sortOrder?: SorterResult<any>["order"];
    filters?: Parameters<GetProp<TableProps, "onChange">>[1];
}

// 后端枚举映射


const TableList: React.FC = () => {
    /**
    * @en-US International configuration
    * @zh-CN 国际化配置
    * */
    const intl = useIntl();
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalOpen, setCreateModalOpen] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [loading, setLoading] = useState(false);
    // const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

    // const [showDetail, setShowDetail] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    // const [currentRow, setCurrentRow] = useState<TruckOrderVo>();
    // const [selectedRowsState, setSelectedRows] = useState<TruckOrderVo[]>([]);
    const [editRow, setEditRow] = useState<TruckOrderServiceFeeVO>();
    //  const [orderStatusEnum, setOrderStatusEnum] = useState<DictType[]>([]);
    const [tabChoice, setTabChoice] = useState<string>("ALL");
    const [selectType, setSelectType] = useState<string>("orderCode");





    const queryPageData = async (pageParams: TruckOrderServiceFeeReqVO) => {
        try {
            setLoading(true);
            const response = await pageListTruckOrderServiceFees(pageParams);
            if (response.code != 0) {
                if (!response.msg) {
                    throw new Error(intl.formatMessage({ id: "request.error.create" }));
                } else {
                    message.error(response.msg);
                }
            }

            return response.data;
        } catch (error) {
            // console.error(error);
            // message.error(intl.formatMessage({ id: "request.error.retry" }));
            message.error(error.message || intl.formatMessage({ id: "request.error.default" }));
            return false;
        } finally {
            setLoading(false);
        }
    };






    const renderKeyValuePairs = (data: Record<string, string>) => (
        <div style={{ whiteSpace: 'pre-line' }}>
            {Object.entries(data).map(([key, value]) => `${key} ${value}`).join('\n')}
        </div>
    );




    const columns: ProColumns<TruckOrderServiceFeeVO>[] = [
              {
            title: intl.formatMessage({ id: 'pages.table.index', defaultMessage: '序号' }),
            valueType: 'index',
            // 可选的自定义序号样式
            render: (text, record, index) => (
                <span>{index + 1}</span>
            ),
            width: 80,
            align: 'center',
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.orderCode"
                    defaultMessage="orderCode"
                />
            ),
            dataIndex: "orderCode",
            key: "orderCode",
            copyable: true,
            disable: true,
            width: 180,
            // ellipsis: true,
            // render: (_, record) => renderKeyValuePairs({
            //     '订单号:': record.orderCode,
            //     '物流单号:': record.trackingNumber || '-',
            //     '物流跟踪号:': record.referenceNo || '-'
            // }),
            
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.trackingNumber"
                    defaultMessage="trackingNumber"
                />
            ),
            dataIndex: "trackingNumber",
            key: "trackingNumber",
            copyable: true,
            disable: true,
            width: 150,            
        },

        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.feeCode"
                    defaultMessage="feeCode"
                />
            ),
            dataIndex: "feeCode",
            key: "feeCode",
            hideInForm: true,
            width: 150,
            ellipsis: true,
            search: false
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.feeValue"
                    defaultMessage="feeValue"
                />
            ),
            dataIndex: "feeValue",
            key: "feeValue",
            search: false,
            hideInForm: true,
            width: 100,
            ellipsis: true,
            render: (_, record) => {
                if (record.currencyCode) {
                    return (record.feeValue || '-') + " " + record.currencyCode;
                } else {
                    return (record.feeValue || '-') + " USD";
                }
            },
        },
        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.serviceAmount"
                    defaultMessage="serviceAmount"
                />
            ),
            dataIndex: "serviceAmount",
            key: "serviceAmount",
            search: false,
            hideInForm: true,
            width: 100,
            ellipsis: true,
            render: (_, record) => {
                if (record.currencyCode) {
                    return (record.serviceAmount || '-') + " " + record.currencyCode;
                } else {
                    return (record.serviceAmount || '-') + " USD";
                }
            },
        },

        {
            title: (
                <FormattedMessage
                    id="pages.truckOrder.createTime"
                    defaultMessage="createTime"
                />
            ),
            dataIndex: "createTime",
            key: "createTime",
            valueType: 'dateRange',
            search: {
                transform: (value) => ({
                    startTime: toUTC(value[0]),
                    endTime: toUTC(value[1],true)
                })
            },
            ellipsis: true,
            render: (_, record) =>
                renderKeyValuePairs({
                    [intl.formatMessage({ id: 'pages.truckOrder.createTime', defaultMessage: '创建:' })]: formatToLocalTime(record.createTime),
                    // "更新:": dayjs(record.updateTime).format("YYYY-MM-DD HH:mm:ss"),
                }),
            hideInForm: true,
            width: 230,
        },
        // {
        //     title: (
        //         <FormattedMessage id="pages.operating" defaultMessage="operating" />
        //     ),
        //     dataIndex: "option",
        //     valueType: "option",
        //     fixed: "right",
        //     width: 120,
        //     disable: true,
        //     render: (_, record) => [
        //         <a
        //             key="view"
        //             onClick={async () => {
        //                 setEditRow(record);
        //                 //   setCreateModalOpen(true);
        //             }}
        //         >
        //             <FormattedMessage id="pages.view" defaultMessage="view" />
        //         </a>,
        //     ],
        // },
    ];

    const [queryParams, setQueryParams] = useState<TruckOrderServiceFeeVO>();

    const pageQueryCustomer = async (params, sorter, filter) => {
        // 表单搜索项会从 params 传入，传递给后端接口。
        console.log(params, sorter, filter);
        const { current, pageSize, orderCode,trackingNumber,startTime,endTime } = params

        const queryParams: TruckOrderServiceFeeReqVO = {
            current: current,
            pageSize: pageSize
        };

        if (orderCode !== undefined) queryParams.orderCode = orderCode;
        if (trackingNumber !== undefined) queryParams.trackingNumber = trackingNumber;
        if (startTime !== undefined && endTime !== undefined) {
            queryParams.beginCreateTime = startTime;
            queryParams.endCreateTime = endTime
        } 
       
        //  console.log(searchParams)
        //  form.submit();

        console.log(queryParams);
        setQueryParams(queryParams);
        return await queryPageData(queryParams);
    }

    const [tableParams, setTableParams] = useState<TableParams>({
        pagination: {
            current: 1,
            pageSize: 20,
        },
    });
    const handleExport = async () => {
        try {
            const params = {
                ...tableParams,
                pageSize: tableParams.pagination?.total,
            };
            const link = document.createElement('a');
            link.href = `/admin-api/system/truck-order/fee_info/export?${qs.stringify(queryParams)}`;
            link.download = 'export.xlsx'; // 指定文件名
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        } catch (error) {
            message.error(intl.formatMessage({ id: 'pages.export.error', defaultMessage: '导出失败' }));
            console.error(error);
        }
    };

    return (
        <PageContainer title={false}>
            <Card
                bordered={false}
                style={{ margin: -16 }} // 消除Card与Tab之间的间距
            >
                <ProTable<TruckOrderServiceFeeVO, API.PageParams>
                    headerTitle={intl.formatMessage({
                        id: "pages.truckOrder.list",
                        defaultMessage: "Order List",
                    })}
                    // actionRef={tabActionRefs.current[item.key]}
                    actionRef={actionRef}
                    loading={loading}
                    // dataSource={dataSource}
                    rowKey="key"
                    // params={tabChoice === item.key ? searchTableParams : {}}
                    // search={false}
                    // pagination={{
                    //     ...tableParams.pagination,
                    //     showSizeChanger: true,
                    //     pageSizeOptions: ["10", "20", "50", "100"],
                    // }}
                    request={pageQueryCustomer}
                    columns={columns}
                    scroll={{
                        x: "max-content", // 自动根据内容宽度计算
                        y: 900, // 固定高度触发垂直滚动
                    }}
                    // toolBarRender={() => [
                    //     <Button
                    //         type="primary"
                    //         key="primary"
                    //         onClick={() => {
                    //             handleExport();
                    //         }}
                    //     >
                    //         <FormattedMessage id="pages.truckOrder.export" defaultMessage="Export" />
                    //     </Button>,
                    // ]}
                    sticky // 表头吸顶
                />
            </Card>
        </PageContainer>
    );
};

export default TableList;
